﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.LIB.YJKControls;
using VerticalMenu.Controls;
using VerticalMenu.Utility;

namespace VerticalMenu
{
	public partial class MainPage : Page, IDockablePaneProvider, IComponentConnector
	{
		private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
		{
			int i = 0;
			while (i < VisualTreeHelper.GetChildrenCount(obj))
			{
				DependencyObject child = VisualTreeHelper.GetChild(obj, i);
				childItem result;
				if (child != null && child is childItem)
				{
					result = (childItem)((object)child);
				}
				else
				{
					childItem childItem2 = this.FindVisualChild<childItem>(child);
					if (childItem2 == null)
					{
						i++;
						continue;
					}
					result = childItem2;
				}
				return result;
			}
			return default(childItem);
		}

		public MainPage(CommandTableInfos commandTableInfos)
		{
			this.InitializeComponent();
			this.InitializeTabControl(commandTableInfos);
			this.m_Handler = new CmdsExternalEventHandler(MainPage.m_CommandData, MainPage.m_Elements);
			this.m_ExternalEvent = ExternalEvent.Create(this.m_Handler);
		}

		public static bool IsInitializedCommandData()
		{
			return MainPage.m_CommandData != null;
		}

		public void SetCommandData(ExternalCommandData commandData)
		{
			MainPage.m_CommandData = commandData;
			if (this.m_Handler != null)
			{
				this.m_Handler.CommandData = commandData;
			}
		}

		public static void Refresh()
		{
			DispatcherFrame dispatcherFrame = new DispatcherFrame();
			Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(MainPage.ExitFrames), dispatcherFrame);
			try
			{
				Dispatcher.PushFrame(dispatcherFrame);
			}
			catch (InvalidOperationException)
			{
			}
		}

		private static object ExitFrames(object frame)
		{
			((DispatcherFrame)frame).Continue = false;
			return null;
		}

		private void InitializeTabControl(CommandTableInfos commandTableInfos)
		{
			this.m_CommandTableInfos = commandTableInfos;
			LeftTabControl leftTabControl = new LeftTabControl();
			leftTabControl.CmndTableInfos = this.m_CommandTableInfos;
			leftTabControl.Initialize();
			leftTabControl.ClickItem += this.mltc_ClickItem;
			leftTabControl.HorizontalAlignment = HorizontalAlignment.Stretch;
			this.mainPanel.Children.Add(leftTabControl);
		}

		private void GetXYDpiScale(ref double xDPICalel, ref double yDPICalel)
		{
			if (MainPage.m_CommandData != null)
			{
				string versionNumber = MainPage.m_CommandData.Application.Application.VersionNumber;
				int num = -1;
				if (this.StringToInt32(versionNumber, ref num))
				{
					if (num <= 2017)
					{
						WinDPIManager.GetWpfXYDpiScale(this, ref xDPICalel, ref yDPICalel);
					}
				}
			}
		}

		private bool StringToInt32(string strValue, ref int nValue)
		{
			bool result;
			try
			{
				nValue = Convert.ToInt32(strValue);
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private double GetXDPIScale()
		{
			this.GetXYDpiScale(ref this.m_XDPIScale, ref this.m_YDPIScale);
			if (Common.Lessthan_Or_Equal(this.m_XDPIScale, 0.0) || Common.GreaterThan(this.m_XDPIScale, 10.0))
			{
				this.m_XDPIScale = 1.0;
			}
			return this.m_XDPIScale;
		}

		private double GetYDPIScale()
		{
			this.GetXYDpiScale(ref this.m_XDPIScale, ref this.m_YDPIScale);
			if (Common.Lessthan_Or_Equal(this.m_YDPIScale, 0.0) || Common.GreaterThan(this.m_YDPIScale, 10.0))
			{
				this.m_YDPIScale = 1.0;
			}
			return this.m_YDPIScale;
		}

		private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			((LeftTabControl)this.mainPanel.Children[0]).AutomaticallyFixToScreenHeight(this.mainPanel.ActualHeight / this.GetYDPIScale());
		}

		private void mltc_ClickItem(object sender, RoutedEventArgs e)
		{
			if (MainPage.m_CommandData != null)
			{
				MainPage.ChangeFocus();
				CommandInfos currentCmdInfos = this.GetCurrentCmdInfos(sender.ToString());
				if (null != currentCmdInfos)
				{
					this.m_Handler.CurrentCmdInfos = currentCmdInfos;
					this.m_ExternalEvent.Raise();
				}
			}
		}

		public void SetupDockablePane(DockablePaneProviderData data)
		{
			data.FrameworkElement = this;
			DockablePaneProviderData dockablePaneProviderData = new DockablePaneProviderData();
			data.InitialState = new DockablePaneState();
			data.InitialState.DockPosition = this.m_position;
			DockablePaneId tabBehind;
			if (this.m_targetGuid == Guid.Empty)
			{
				tabBehind = null;
			}
			else
			{
				tabBehind = new DockablePaneId(this.m_targetGuid);
			}
            if ((int)this.m_position == 59424)
			{
				data.InitialState.TabBehind = tabBehind;
			}
            if ((int)this.m_position == 59423)
			{
				RevitVersionFuncs.SetFloatingRectangle(ref data, this.m_left, this.m_top, this.m_right, this.m_bottom);
			}
		}

		public void SetInitialDockingParameters(int left, int right, int top, int bottom, DockPosition position, Guid targetGuid)
		{
			this.m_position = position;
			this.m_left = left;
			this.m_right = right;
			this.m_top = top;
			this.m_bottom = bottom;
			this.m_targetGuid = targetGuid;
		}

		private CommandInfos GetCurrentCmdInfos(string indexInfo)
		{
			CommandInfos result;
			try
			{
				int num = indexInfo.IndexOf(".");
				string value = indexInfo.Substring(0, num);
				string value2 = indexInfo.Substring(num + 1, indexInfo.Length - num - 1);
				int index = Convert.ToInt32(value);
				int index2 = Convert.ToInt32(value2);
				CommandInfos commandInfos = this.m_CommandTableInfos.TableInofList[index].CommandInfoList[index2];
				result = commandInfos;
			}
			catch (Exception)
			{
				result = null;
			}
			return result;
		}

		private static void ChangeFocus()
		{
			try
			{
				UIApplication application = MainPage.m_CommandData.Application;
				View activeView = application.ActiveUIDocument.ActiveView;
				IList<UIView> openUIViews = application.ActiveUIDocument.GetOpenUIViews();
				foreach (UIView uiview in openUIViews)
				{
					if (activeView == null || uiview.ViewId.IntegerValue != activeView.Id.IntegerValue)
					{
						View view = MainPage.m_CommandData.Application.ActiveUIDocument.Document.GetElement(uiview.ViewId) as Autodesk.Revit.DB.View;
						application.ActiveUIDocument.ActiveView = view;
						application.ActiveUIDocument.ActiveView = activeView;
						return;
					}
				}
				FilteredElementCollector filteredElementCollector = new FilteredElementCollector(application.ActiveUIDocument.Document);
				FilteredElementIterator elementIterator = filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
				elementIterator.Reset();
				while (elementIterator.MoveNext())
				{
					Element element = elementIterator.Current;
					View view = element as Autodesk.Revit.DB.View;
					if (view != null && !view.IsTemplate)
					{
						if (view.Id.IntegerValue != activeView.Id.IntegerValue)
						{
							if ((int)view.ViewType == 1 || (int)view.ViewType == 2 || (int)view.ViewType == 117 || (int)view.ViewType == 4 || (int)view.ViewType == 3)
							{
								application.ActiveUIDocument.ActiveView = view;
								application.ActiveUIDocument.ActiveView = activeView;
								break;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				string message = ex.Message;
			}
		}

		private void DockableDialogs_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			this.mainPanel.Width = base.Width / this.GetXDPIScale();
			((LeftTabControl)this.mainPanel.Children[0]).Width = this.mainPanel.Width;
		}

        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //[DebuggerNonUserCode]
        //public void InitializeComponent()
        //{
        //    if (!this._contentLoaded)
        //    {
        //        this._contentLoaded = true;
        //        Uri resourceLocator = new Uri("/VerticalMenu;component/mainpage/mainpage.xaml", UriKind.Relative);
        //        Application.LoadComponent(this, resourceLocator);
        //    }
        //}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //[EditorBrowsable(EditorBrowsableState.Never)]
        //void IComponentConnector.Connect(int connectionId, object target)
        //{
        //    switch (connectionId)
        //    {
        //    case 1:
        //        this.DockableDialogs = (MainPage)target;
        //        this.DockableDialogs.SizeChanged += this.DockableDialogs_SizeChanged;
        //        break;
        //    case 2:
        //        this.mainPanel = (Canvas)target;
        //        this.mainPanel.SizeChanged += this.Window_SizeChanged;
        //        break;
        //    default:
        //        this._contentLoaded = true;
        //        break;
        //    }
        //}

		private static ExternalCommandData m_CommandData = null;

		private static ElementSet m_Elements = new ElementSet();

		private Guid m_targetGuid;

        private DockPosition m_position = (DockPosition)59422;

		private int m_left = 1;

		private int m_right = 1;

		private int m_top = 1;

		private int m_bottom = 1;

		private double m_XDPIScale = 0.0;

		private double m_YDPIScale = 0.0;

		private CommandTableInfos m_CommandTableInfos = null;

		private ExternalEvent m_ExternalEvent = null;

		private CmdsExternalEventHandler m_Handler = null;

		//internal MainPage DockableDialogs;

        //private Canvas mainPanel;

		//private bool _contentLoaded;
	}
}
